package org.ihelpuoo.parser.segment;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;

import org.ihelpuoo.lang.ObjectUtils;

public class SegmentUtils
{
	public static Segment fillByObject(Segment seg, Object obj)
	{
		if (null == obj || null == seg)
			return seg;
		Class klass = obj.getClass();
		Field[] fs = ObjectUtils.getAllMyStdFields(klass);
		for (int i = 0; i < fs.length; i++)
		{
			Field f = fs[i];
			Object v = null;
			try
			{
				v = ObjectUtils.getGetter(klass,f).invoke(obj);
			}
			catch (Exception e)
			{
				if (f.isAccessible())
					try
					{
						v = f.get(obj);
					}
					catch (Exception e1)
					{
					}
			}
			if (v != null)
				seg.set(f.getName(),v);
			else
				seg.set(f.getName(),"");
		}
		return seg;
	}

	public static Segment fillBySegment(Segment seg, Object obj)
	{
		if (null == obj || null == seg)
			return seg;
		Iterator<String> it = seg.iterator();
		Class klass = obj.getClass();
		while (it.hasNext())
		{
			String key = it.next();
			try
			{
				Method getter = ObjectUtils.getGetter(klass,key);
				Object v = getter.invoke(obj);
				seg.set(key,v);
			}
			catch (Exception e)
			{
				seg.set(key,"");
			}
		}
		return seg;
	}

	public static Segment fillSegment(Segment seg, Map<String, ?> map)
	{
		if (null == map || null == seg)
			return seg;
		Iterator<String> it = seg.iterator();
		while (it.hasNext())
		{
			String key = it.next();
			Object v = map.get(key);
			seg.set(key,v);
		}
		return seg;
	}
	
}
